package managedbean;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.event.ActionEvent;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.Date;
import javax.ejb.EJB;
import session.stateless.EmployeeSessionBeanLocal;
import javax.faces.bean.ManagedProperty;
import entity.Employee;
import entity.Notice;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.TimeZone;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import managedbean.EmailManager;
import managedbean.NoticeManagerBean;
import managedbean.UserSessionManagerBean;
import session.stateless.LogSessionBeanLocal;
import session.stateless.NoticeSessionBeanLocal;

@ManagedBean(name = "profileManagerBean")
@RequestScoped
public class ProfileManagerBean {

    @ManagedProperty(value = "#{userSessionManagerBean}")
    private UserSessionManagerBean userSessionManagerBean;
    @EJB
    EmployeeSessionBeanLocal employeeSessionBeanLocal;
    private NoticeManagerBean noticeManagerBean = new NoticeManagerBean();
    @EJB
    private NoticeSessionBeanLocal noticeSessionBeanLocal;
    @EJB
    private LogSessionBeanLocal logSessionBeanLocal;
    private String userId;
    private String userPassword;
    private String name;
    private Integer contactOffice;
    private Integer contactMobile;
    private String emailAddress;
    private String department;
    private String accountStatus;
    @Temporal(value = TemporalType.DATE)
    private Date passwordExpiry;
    private Integer invalidCounter;
    private String designation;
    private Employee employee;
    private ArrayList<Employee> employees;
    @Temporal(value = TemporalType.DATE)
    private Date dob;
    private String newUserPassword;
    private String newUserPassword2;
    private String status;
    private String loadProfile;
    private String loadChangePassword;
    private String loadIndex;
    private String loadSuccess;
    private String header;
    private String message;
    private String message2;
    private String link;
    private static String url;
    private ArrayList <Notice> notices = new  ArrayList <Notice> () ;
    private TimeZone tz;

    public ProfileManagerBean() {
    }

    public String getLoadIndex() {
        userSessionManagerBean.clearSession();
        try {
            setTz(TimeZone.getDefault());
            
            employee = employeeSessionBeanLocal.getEmployee(userSessionManagerBean.getUserId());
            
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            cal.add(cal.DAY_OF_MONTH, -7);
            Date d = cal.getTime();

            List<Notice> temp = noticeSessionBeanLocal.getNotices();
            
            for (Notice a : temp) {
                if (a.getNoticeDate().after(d)) {
                    String[] items = a.getDepartment().split(";");
                    
                    for (int q = 0; q < items.length; q++) {
                        if (employee.getDepartment().contains(items[q])) {
                            notices.add(a);
                        }

                    }
                }
                
                HashSet set = new HashSet(notices);
                
                notices.clear();
                notices.addAll(set);
                
                Collections.sort(notices);
            }
        } catch (Exception exception) {
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort()
                        + "/MerlionERP-war/login.xhtml");
            } catch (Exception ex) {
            }
            System.out.println("ERROR AT ProfileManagerBean getLoadIndex()");
            exception.printStackTrace();
        }

        return null;
    }

    public String getLoadProfile() {
        userId = getUserSessionManagerBean().getUserId();
        
        if (userId != null) {
            setUpdateProfile();
        } else {
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort()
                        + "/MerlionERP-war/login.xhtml");
            } catch (Exception ex) {
                System.out.println("ERROR AT ProfileManagerBean getLoadProfile");
                ex.printStackTrace();
            }
        }

        return null;
    }

    public String getLoadChangePassword() {
        userId = userSessionManagerBean.getUserId();

        if (userSessionManagerBean.getOTP()) {
            status = "Password expired. Please change your password before proceeding.";
        }

        return null;
    }

    public String getLoadSuccess() {
        if (userSessionManagerBean.getSelectedItem() != null) {
            ArrayList<String> al = (ArrayList<String>) userSessionManagerBean.getSelectedItem();
            userSessionManagerBean.clearSession();
            header = al.get(0);
            message = al.get(1);
            message2 = al.get(2);
            link = al.get(3);
            url = al.get(4);
        }
        
        return null;
    }

// <editor-fold defaultstate="collapsed" desc="Getter & Setter methods. Click on the + sign on the left to edit the code.">
    /**
     * @param forgetPassword the forgetPassword to set
     */
    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getContactOffice() {
        return contactOffice;
    }

    public void setContactOffice(Integer contactOffice) {
        this.contactOffice = contactOffice;
    }

    public Integer getContactMobile() {
        return contactMobile;
    }

    public void setContactMobile(Integer contactMobile) {
        this.contactMobile = contactMobile;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getAccountStatus() {
        return accountStatus;
    }

    public void setAccountStatus(String accountStatus) {
        this.accountStatus = accountStatus;
    }

    public Date getPasswordExpiry() {
        return passwordExpiry;
    }

    public void setPasswordExpiry(Date passwordExpiry) {
        this.passwordExpiry = passwordExpiry;
    }

    public Integer getInvalidCounter() {
        return invalidCounter;
    }

    public void setInvalidCounter(Integer invalidCounter) {
        this.invalidCounter = invalidCounter;
    }

    public String getDesignation() {
        return designation;
    }

    public void setDesignation(String designation) {
        this.designation = designation;
    }

    public UserSessionManagerBean getUserSessionManagerBean() {
        return userSessionManagerBean;
    }

    public void setUserSessionManagerBean(UserSessionManagerBean userSessionManagerBean) {
        this.userSessionManagerBean = userSessionManagerBean;
    }

    public Employee getEmployee() {
        return employee;
    }

    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

    public ArrayList<Employee> getEmployees() {
        return employees;
    }

    public void setEmployees(ArrayList<Employee> employees) {
        this.employees = employees;
    }

    public Date getDob() {
        return dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }

    public String getNewUserPassword() {
        return newUserPassword;
    }

    public void setNewUserPassword(String newUserPassword) {
        this.newUserPassword = newUserPassword;
    }

    public String getNewUserPassword2() {
        return newUserPassword2;
    }

    public void setNewUserPassword2(String newUserPassword2) {
        this.newUserPassword2 = newUserPassword2;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public void setLoadIndex(String loadIndex) {
        this.loadIndex = loadIndex;
    }

    public void setLoadProfile(String loadProfile) {
        this.loadProfile = loadProfile;
    }

    public void setLoadChangePassword(String loadChangePassword) {
        this.loadChangePassword = loadChangePassword;
    }

    /**
     * @return the header
     */
    public String getHeader() {
        return header;
    }

    /**
     * @param header the header to set
     */
    public void setHeader(String header) {
        this.header = header;
    }

    /**
     * @return the message
     */
    public String getMessage() {
        return message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(String message) {
        this.message = message;
    }

    /**
     * @return the message2
     */
    public String getMessage2() {
        return message2;
    }

    /**
     * @param message2 the message2 to set
     */
    public void setMessage2(String message2) {
        this.message2 = message2;
    }

    /**
     * @return the link
     */
    public String getLink() {
        return link;
    }

    /**
     * @param link the link to set
     */
    public void setLink(String link) {
        this.link = link;
    }

    /**
     * @param loadSuccess the loadSuccess to set
     */
    public void setLoadSuccess(String loadSuccess) {
        this.loadSuccess = loadSuccess;
    }

    /**
     * @return the noticeManagerBean
     */
    public NoticeManagerBean getNoticeManagerBean() {
        return noticeManagerBean;
    }

    /**
     * @param noticeManagerBean the noticeManagerBean to set
     */
    public void setNoticeManagerBean(NoticeManagerBean noticeManagerBean) {
        this.noticeManagerBean = noticeManagerBean;
    }

    /**
     * @return the notices
     */
    public ArrayList<Notice> getNotices() {
        return notices;
    }

    /**
     * @param notices the notices to set
     */
    public void setNotices(ArrayList<Notice> notices) {
        this.notices = notices;
    }

    /**
     * @return the tz
     */
    public TimeZone getTz() {
        return tz;
    }

    /**
     * @param tz the tz to set
     */
    public void setTz(TimeZone tz) {
        this.tz = tz;
    }

// </editor-fold>
    public void setUpdateProfile() {
        setEmployee(employeeSessionBeanLocal.getEmployee(userId));
        setName(getEmployee().getName());
        setDepartment(getEmployee().getDepartment());
        setDesignation(getEmployee().getDesignation());
        setContactOffice(getEmployee().getContactOffice());
        setContactMobile(getEmployee().getContactMobile());
        setEmailAddress(getEmployee().getEmailAddress());
        setUserPassword(getEmployee().getUserPassword());
        setAccountStatus(getEmployee().getAccountStatus());
        setPasswordExpiry(getEmployee().getPasswordExpiry());
        setInvalidCounter(getEmployee().getInvalidCounter());
        setDob(getEmployee().getDob());
    }

    public void updateProfile(ActionEvent event) {
        try {
            employeeSessionBeanLocal.updateEmployee(userId, name, contactOffice, contactMobile, emailAddress, department, accountStatus, passwordExpiry, invalidCounter, designation, dob);

            logSessionBeanLocal.addLog("Update employee", "Employee account updated: " + userId, "profile.xhtml", userSessionManagerBean.getUserId());

            ArrayList<String> al = new ArrayList<String>();
            al.add("Profile updated");
            al.add("You have successfully updated your profile. Please be reminded that you need to change your password every 90 days.");
            al.add("Click on the link to return to ");
            al.add("Profile page");
            al.add("profile.xhtml");
            userSessionManagerBean.setSelectedItem(al);

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                    + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort()
                    + "/MerlionERP-war/success.xhtml");

        } catch (Exception ex) {
        }
    }

    public void changePassword(ActionEvent event) {
        this.userId = getUserSessionManagerBean().getUserId();
        if (employeeSessionBeanLocal.loginEmployee(userId, userPassword) > 0) {
            if (newUserPassword.compareTo(newUserPassword2) == 0) {
                if (userPassword.compareTo(newUserPassword) == 0) {
                    setStatus("You must enter a new password.");
                } else {
                    Date d = employeeSessionBeanLocal.updatePassword(userId, newUserPassword);

                    logSessionBeanLocal.addLog("Update employee", "Password change: " + userId, "profile.xhtml", userSessionManagerBean.getUserId());

                    userSessionManagerBean.setOTP(Boolean.FALSE);

                    ArrayList<String> al = new ArrayList<String>();
                    al.add("Password updated");
                    al.add("You have successfully updated your password. Please be reminded that you need to change your password every 90 days.");
                    al.add("Click on the link to return to ");
                    al.add("continue");
                    al.add("profile.xhtml");
                    userSessionManagerBean.setSelectedItem(al);
                    try {

                        FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                                + userSessionManagerBean.getServerName() + ":"
                                + userSessionManagerBean.getServerPort()
                                + "/MerlionERP-war/success.xhtml");
                    } catch (Exception ex) {
                    }
                }


            } else {
                setStatus("You must enter the same password twice in order to confirm it.");
            }
        } else {
            setStatus("Your old password is incorrect.");
        }

    }

    public void redirect(ActionEvent event) {
        try {

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                    + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort()
                    + "/MerlionERP-war/" + url);
        } catch (Exception ex) {
        }

    }

    public void profile(ActionEvent event) {

        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                    + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort()
                    + "/MerlionERP-war/profile.xhtml");
        } catch (Exception ex) {
        }
    }

    public void logout(ActionEvent event) {
        userSessionManagerBean.clearSession();
        userSessionManagerBean.setName(null);
        userSessionManagerBean.setAddressList(null);

        logSessionBeanLocal.addLog("Logout", "Account logout: " + userSessionManagerBean.getUserId(), "index.xhtml", userSessionManagerBean.getUserId());
        userSessionManagerBean.setUserId(null);
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                    + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort()
                    + "/MerlionERP-war/login.xhtml");
        } catch (Exception ex) {
        }
    }

    public void sendMessage(ActionEvent event) { //to send a message to the owner of profile
        try {
            userSessionManagerBean.setReceivers("");
            userSessionManagerBean.setReceivers(userSessionManagerBean.getSelectedContact().getUserId() + ",");

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                    + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort()
                    + "/MerlionERP-war/sendMessage.xhtml"); //redirect to sendMessage.xhtml
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void forget(ActionEvent event) {
        Boolean success = true;
        Employee employee = employeeSessionBeanLocal.getEmployee(userId);



        if (employee != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            String temp = sdf.format(employee.getDob());

            if (temp.compareTo(message) != 0) {
                success = false;
            }
            if (employee.getEmailAddress().compareTo(emailAddress) != 0) {
                success = false;
            }


        } else {
            success = false;
        }

        if (success) {
            String temp = Long.toHexString(Double.doubleToLongBits(Math.random())).substring(0, 8);
            setUserPassword(temp);
            Calendar cal = Calendar.getInstance();
            Date d = new Date();
            cal.setTime(d);
            setPasswordExpiry(d);
            employeeSessionBeanLocal.updatePassword(userId, userPassword, passwordExpiry);
            EmailManager em = new EmailManager();
            em.sendEmail("[REQUEST] Password reset", "Dear " + userId + ",\n\n" +"We have received your request on " + cal.getTime().toString() + " and we have reset your password.\n\nYou can access your account using the new ONE-TIME-PASSWORD: " + temp
                    + "\n\nYou are required to change your password on the first account. \n\nShould you have any query, please reach us at 6886 2000. \n\nThank you. \n\nRegard,\nIT support team\n\n*This is a system generated message, no reply is required. ", "mf.merlionerp@gmail.com", emailAddress, "merlionfood");
            logSessionBeanLocal.addLog("Update employee", "Password reset: " + userId, "forget.xhtml", userId);
            ArrayList<String> al = new ArrayList<String>();
            al.add("Password recovered");
            al.add("You have successfully recovered your password. Please be reminded that you need to change your O-T-P on first login.");
            al.add("Click on the link to return to ");
            al.add("continue");
            al.add("login.xhtml");
            userSessionManagerBean.setSelectedItem(al);
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort()
                        + "/MerlionERP-war/success.xhtml");
            } catch (Exception ex) {
                userSessionManagerBean.setStatus(ex.toString());
            }
        } else {
            status = "* One or more fields have not been filled correctly";
        }

    }
}
